/*
 * @Author: 王汝鹏
 * @Date: 2021-01-04 10:31:26
 * @LastEditTime: 2021-01-12 17:27:05
 * @LastEditors: Please set LastEditors
 * @Description: 生成规则块数据程序
 * @FilePath: \mock_-device_-data\test2.js
 */

const { outputJsonSync } = require("fs-extra");


//  生成块数据方法-正方形
const draw_block = function(board, x, y, width, height, type) {
  for (let r=y; r<y+height; r++) {
    for (let c=x; c<x+width; c++) {
      board[r][c] = 10000;
    }
  }
}
//  绘制块数据方法-圆形
const draw_block_circle = function(board, x, y, width, height, type) {
  //  临时画板, 用于绘制图形, 然后搬移到大画板上, 避免计算坐标的麻烦
  let circle_board = new Array(height);
  for (let r=0; r<height; r++) {
    circle_board[r] = new Array(width);
  }

  //  在临时画板上绘制圆形
  for (let r=0; r<height; r++) {
    //  圆行半径
    let R = width / 2;
    //  计算y坐标对应的弧长
    //  a² + b² = c² => (弧长一半)² + (弧线到远点距离一半)² = (半径)²
    let c = R;
    let b = Math.abs(R-r);
    let a = Math.sqrt(c*c - b*b);

    //  计算弧线的x起始坐标
    let x_start = Math.round(R - a);
    let x_end   = Math.round(R + a);
    
    for (let c=x_start; c<=x_end; c++) {
      circle_board[r][c] = 10000;
    }
  }

  //  将临时画板数据绘制到大画板上
  for (let r=0; r<height; r++) {
    for (let c=0; c<width; c++) {
      if (circle_board[r][c])
        board[y+r][x+c] = circle_board[r][c];
    }
  }
}

//  随机生成n块数据
const make_n_block_file = function(board, n, width, height) {
  let length = Math.ceil(Math.sqrt(n));
  let w = Math.round(width  / length - 2);
  let h = Math.round(height / length - 2);

  console.log(`n=${n}, length=${length}, w=${w}, h=${h}`);

  for (let i=0; i<length; i++) {
    let y = (h+1) * i;
    for (let j=0; j<length; j++) {
      let x = (w+2) * j;
      draw_block_circle(board, x, y, w, h);
    }
  }
}


const ROW_LENGTH    = 512;
const COLUMN_LENGTH = 512;

let id = 0;
let temp_id = 0;


for (let i=0; i<10; i++) {
  //  画板初始化, 创建二维数组 width * height
  let board = new Array(ROW_LENGTH);
  for (let j=0; j<ROW_LENGTH; j++) {
    board[j] = new Array(COLUMN_LENGTH);
    board[j].fill(52000);
  }

  //  生成包含n块的文件
  make_n_block_file(board, 100, COLUMN_LENGTH, ROW_LENGTH);
  // draw_block(board, 0, 0, COLUMN_LENGTH, ROW_LENGTH/2);
  
  //  转换每行数据
  let out_data = [];
  for (let i=0; i<ROW_LENGTH; i++) {
    out_data.push({
      id     : id++,
      temp_id: temp_id++,
      LE     : board[i],
      HE     : board[i]
    })
  }

  //  输出文件
  outputJsonSync(`./data_2/${i+1}.data`, out_data);
}

